package com.woniuxy.mail.rabbit_demo.listener;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.mail.rabbit_demo.entity.Order;
import com.woniuxy.mail.rabbit_demo.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;

/**
 * 下订单成功发送邮件
 */
@Slf4j
@Component
public class MyListener {
    @Autowired
    private EmailService emailService;

    /**
     * 监听某个队列的消息
     * @param message 接收到的消息
     */
    @RabbitListener(queues = "order_add_email_queue")//这里表示的是监听order_add_email_queue这个队列的消息
    public void myListener1(String message){
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Order order = objectMapper.readValue(message, Order.class);
            Context context = new Context();
            context.setVariable("order",order);
            //sender表示的是发送者,accepter表示的是接收者
            emailService.sendEmail("下单成功",context,"1558788078@qq.com","1558788078@qq.com","email1.html");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
